package com.lnj.messages.utiles;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class JsonUtil {
    private final ObjectMapper om = new ObjectMapper();

    // 定义自定义的日期时间格式（可选）
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);

    @PostConstruct
    public void init(){
        // 创建一个自定义的 JavaTimeModule
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 为 LocalDateTime 注册自定义的序列化器和反序列化器（可选）
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(FORMATTER));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(FORMATTER));

        // 注册模块
        om.registerModule(javaTimeModule);

        // （可选）禁用将日期写为时间戳的功能，强制使用文本格式
        // om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    public String toJson(Object o){
        try {
            return om.writeValueAsString(o);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T fromJson(String json,Class<T> tClass){
        try {
            return om.readValue(json,tClass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
